package cn.jhc.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    private static final String CONNECTION_URL = "jdbc:mysql://localhost/questions?user=quser&password=123456&serverTimezone=GMT";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        boolean loginSuccess = false;
        try(Connection connection = DriverManager.getConnection(CONNECTION_URL)) {
            try(Statement statement = connection.createStatement()) {
                try(ResultSet resultSet = statement.executeQuery("select count(id) from user where username='" + username + "' " +
                        "and pass='" + password + "'")) {
                    resultSet.next();
                    int count = resultSet.getInt(1);
                    if (count == 1) {
                        loginSuccess = true;
                    }
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        resp.setHeader("Content-Type", "application/json");
        resp.getWriter().println("{\"ok\":" + loginSuccess + "}");
    }
}

